<template>
  <div class="editForm-wrapper">
    <!-- 结算人编辑dialog-->
    <el-dialog :title="title" :close-on-click-modal="false" v-dialogDrag :visible.sync="editVisible">
      <el-form label-width="110px" :rules="dataRule" ref="editForm" :model="editForm">
        <el-form-item label="结算人类型:" prop="types">
          <el-radio-group v-model="editForm.types" @change="changeHandlerType">
            <el-radio v-for="item in $dictUtils.getDictList('companyType')" :key="item.value" :label="Number(item.value)">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="结算人名称:" prop="names" :rules="[
                  {required: true, message:'姓名不能为空', trigger:'blur'},
                  {validator: validator.isName, trigger:'blur'},
                  {validator: getCompanyClientByName, trigger:'blur'}
                 ]">
          <el-input v-model="editForm.names"></el-input>
        </el-form-item>
        <el-form-item prop="codes" style="position: relative" v-if="editForm.types!==Number($dictUtils.getDictList('companyType')[0].value)"
          disabled :rules=" [
          { required: editForm.types !== Number($dictUtils.getDictList('companyType')[0].value), message: '社会信用统一代码不能为空', trigger: 'blur' },
          {validator:checkRepeatCode, trigger:'blur'}
        ]">
          <section style="position: absolute; left: -143px; font-size: 16px">
            <span style="color:red">*</span>统一社会信用代码:
          </section>

          <el-input v-model="editForm.codes" :disabled="method==='edit'"></el-input>
        </el-form-item>
        <el-form-item label="身份证号:" prop="idCard" :rules=" [
          { required: editForm.types === Number($dictUtils.getDictList('companyType')[0].value), message: '身份证不能为空', trigger: 'blur' },
          {validator: validator.isCardId, trigger:'blur'},
            {validator: getCompanyClientByidCard, trigger:'blur'}
        ]">
          <el-input v-model="editForm.idCard" :disabled="method==='edit'"></el-input>
        </el-form-item>
        <el-form-item label="联系人姓名:" prop="contactName">
          <el-input v-model="editForm.contactName"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话:" prop="contactPhone" :rules=" [ {validator:checkPhoneNumber, trigger:'blur'}]">
          <el-input v-model="editForm.contactPhone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div class="footer-input">
          <el-button size="small" type="primary" @click="doSubmit()" v-noMoreClick>确定</el-button>
          <el-button size="small" @click="close()">取消</el-button>
        </div>

      </span>
    </el-dialog>
    <el-dialog :title="title" width="480px" :close-on-click-modal="false" v-dialogDrag :visible.sync="detailsVisible">
      <section class="view-container">
        <section class="label-container">类型：</section>
        <section class="form-container">
          <el-radio-group :disabled="method === 'view'" v-model="viewForm.types">
            <el-radio :label="2">个人</el-radio>
            <el-radio :label="1">企业</el-radio>
          </el-radio-group>
        </section>
      </section>
      <section class="view-container">
        <section class="label-container">结算人名称：</section>
        <section class="form-container">{{ viewForm.names }}</section>
      </section>
      <section class="view-container">
        <section class="label-container">统一社会信用代码:：</section>
        <section class="form-container">{{ viewForm.codes }}</section>
      </section>
      <section class="view-container">
        <section class="label-container">身份证号：</section>
        <section class="form-container">{{ viewForm.idCard }}</section>
      </section>
      <section class="view-container">
        <section class="label-container">联系人姓名：</section>
        <section class="form-container">{{ viewForm.contactName }}</section>
      </section>
      <section class="view-container">
        <section class="label-container">联系人电话：</section>
        <section class="form-container">{{ viewForm.contactPhone }}</section>
      </section>
    </el-dialog>
    <CompanyDialog ref="CompanyDialog" @getCompanyData="getCompanyData"></CompanyDialog>
  </div>
</template>
<script>
  import {
    edit,
    checkRepeat
  } from '@/api/market/crm.js'
  import CompanyDialog from '@/components/dialog/queryAllCompanyDialog.vue'
  export default {
    components: {
      CompanyDialog
    },
    data() {
      return {
        areaLabel: {},
        method: '',
        title: '',
        editForm: {
          types: 1,
          names: '',
          codes: '',
          idCard: '',
          contactName: '',
          contactPhone: '',
          id: '',
          addressId: ''
        },
        viewForm: {
          types: '',
          names: '',
          codes: '',
          idCard: '',
          contactName: '',
          contactPhone: '',
          id: '',
          addressId: ''
        },
        editVisible: false,
        detailsVisible: false,
        dataRule: {
          names: [{
            required: true,
            message: '请输入结算人名称',
            trigger: 'blur'
          }],
          types: [{
            required: true,
            message: '请选择结算人类型',
            trigger: 'change'
          }],
          contactPhone: [{
            required: true,
            message: '请输入联系人电话',
            trigger: 'blur'
          }],
          contactName: [{
            required: true,
            message: '请输入联系人姓名',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
    	handleClose(done) {
			this.$Msg.confirm({
				title:'您确定要关闭吗？',
				content:this.GLOBAL.FORM_CLOSE_TIPS,
				confirmCall:()=>{
					done();
				}
			})
		},
      init(method, editForm) {
        if (method === 'add') {
          this.editVisible = true
          this.method = method
          this.$nextTick(() => {
            this.$refs.editForm.resetFields()
            this.$nextTick(() => {})
          })

          this.editForm.id = ''
          this.editForm.addressId = ''
          this.title = '新增结算人'
        } else if (method === 'edit') {
          this.editVisible = true
          this.method = method
          this.title = '编辑结算人'
          this.editForm.id = editForm.id
          if (editForm.countyCode !== '' && typeof editForm.countyCode !== 'undefined') {}
          this.$nextTick(() => {
            this.$refs.editForm.resetFields()
            if (method === 'edit') { // 修改或者查看
              this.loading = true
              this.$http({
                url: `/truck/payee/queryById?id=${this.editForm.id}`,
                method: 'get'
              }).then(({
                data
              }) => {
                if (data.success) {
                  this.editForm = this.recover(this.editForm, data.result)
                  this.loading = false
                } else {
                  this.loading = false
                  this.visible = false
                }
              })
            }
          })
        } else if (method === 'view') {
          this.method = method
          this.viewForm = editForm
          this.detailsVisible = true
          this.title = '结算人详情'
          let areaLabel = JSON.parse(this.viewForm.countyCode)
          getAreaByCode(areaLabel).then((res) => {
            if (res.data.code === '200') {
              this.areaLabel = res.data.result.list[0]
            }
          })
        }
      },
      close() {
        this.editVisible = false
      },
      doSubmit() {
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/truck/payee/save`,
              method: 'post',
              data: this.editForm,
              headers: {
                'Content-Type': 'application/json; charset=utf-8'
              }
            }).then(({
              data
            }) => {
              if (data && data.code === '200') {
                this.editVisible = false
                this.$message.success(data.message)
                this.$emit('refreshDataList')
              }
            })
          }
        })
      },

      // 校验手机号
      checkPhoneNumber(rule, value, callback) {
        if (value && (!(/^[1][34578]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
          callback(new Error('手机号码不符合规范'))
        } else {
          callback()
        }
      },
      // 选择结算人类型
      changeHandlerType(e) {
        this.editForm.types = e
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      // 往来选择弹窗
      getCompanyClientByName() {
        if (this.editForm.names) {
          this.$nextTick(() => {
            this.$refs['CompanyDialog'].getCompanyList(this.$refs['CompanyDialog'].page, this.editForm.names)
            this.$refs['CompanyDialog'].dialogVisible = true
          })

        }
      },
      // 往来选择弹窗
      getCompanyClientByidCard() {
        if (this.editForm.idCard) {
          this.$nextTick(() => {
            this.$refs['CompanyDialog'].getCompanyList(this.$refs['CompanyDialog'].page, '', this.editForm.idCard)
            this.$refs['CompanyDialog'].dialogVisible = true
          })
        }
      },
      // 客户选择数据回显
      getCompanyData(row) {
        this.editForm.names = row.names
        this.editForm.contactName = row.contactName
        this.editForm.contactPhone = row.contactPhone
        this.editForm.idCard = row.idCard
        this.editForm.codes = row.codes
        this.dialogVisible = false
      },
      // 身份证重复
      checkRepeatIdCard(rule, value, callback) {
        if (this.method === 'edit') {
          return callback()
        }
        if (value && (!(/\d{17}[\d|x]|\d{15}/).test(value) || (value.length !== 15 && value.length !== 18))) {
          callback(new Error('身份证号码不符合规范'))
        } else {
          callback()
        }
        if (value) {
          checkRepeat({
            props: '5',
            idCard: value
          }).then(res => {
            if (res.data.code !== '200') {
              callback(new Error('结算人身份证有重复'))
            } else {
              callback()
            }
          })
        } else {
          callback()
        }
      },
      // 社会统一代码重复
      checkRepeatCode(rule, value, callback) {
        if (this.method === 'edit') {
          return callback()
        }
        if (value) {
          checkRepeat({
            props: '5',
            codes: value
          }).then(res => {
            if (res.data.code !== '200') {
              callback(new Error('结算人信用代码有重复'))
            } else {
              callback()
            }
          })
        } else {
          callback()
        }
      }
    },
    mounted() {

    }
  }
</script>
<style lang="scss" scoped>
  .view-container {
    margin-bottom: 20px;
    display: flex;

    .label-container {
      width: 150px;
      text-align: right;
      font-size: 16px;
      font-weight: 400;
      color: #666666;
    }

    .form-container {
      font-size: 14px;
      font-weight: 400;
      color: #333333;
      width: 200px;
    }
  }
</style>
